<template>
  <div>
    <el-dialog title="编辑机构" :visible.sync="dialogVisible" width="500px" :before-close="closeDialog"
      :close-on-click-modal="false" :append-to-body="true">
      <el-form :model="editForm" :rules="rules" ref="refForm" label-width="80px">

        <el-form-item size="small" label="上级机构" prop="parentId" v-if="editForm.type!=1">
          <TreeSelSearch style="width: 100%" ref="refTreeSelSearch" @changeOrgId="changeOrgId" :disabled="true" :orgName="editForm.parentName">
          </TreeSelSearch>
        </el-form-item>

        <el-form-item size="small" label="机构属性" prop="type" v-if="editForm.type!='1'">
          <el-select disabled clearable v-model="editForm.type" style="width: 100%" placeholder="请选择">
            <el-option v-for="item in agencyTypeList" :label="item.name" :value="item.id" :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item m-item size="small" label="机构名称" prop="orgName">
          <el-input clearable v-model.trim="editForm.orgName" placeholder="请输入" :disabled="editForm.type==3"
            oninput="value=value.replace(/\s*/g,'')" @blur="editForm.orgName = $event.target.value" maxlength="20">
          </el-input>
        </el-form-item>

        <!-- <el-form-item size="small" label="地区" prop="streetCode" >
              <div style="display: flex; align-items: center">
                <el-select v-model="editForm.provinceCode" placeholder="省" @change="changprovince" style="width: 400px;margin-right: 5px;">
                  <el-option v-for="(item, i) in provinceList" :key="i" :label="item.regionName"
                    :value="item.regionCode">
                  </el-option>
                </el-select>
                <el-select v-model="editForm.cityCode" placeholder="市" @change="changcity" style="width: 400px;margin-right: 5px;">
                  <el-option v-for="(item, i) in cityList" :key="i" :label="item.regionName" :value="item.regionCode">
                  </el-option>
                </el-select>
                <el-select v-model="editForm.areaCode" placeholder="区" @change="changarea" style="width: 400px;margin-right: 5px;">
                  <el-option v-for="(item, i) in areaList" :key="i" :label="item.regionName" :value="item.regionCode">
                  </el-option>
                </el-select>
                <el-select v-model="editForm.streetCode" placeholder="街道" @change="changestreet" style="width: 400px">
                  <el-option v-for="(item, i) in streetList" :key="i" :label="item.regionName" :value="item.regionCode">
                  </el-option>
                </el-select>
                <i class="iconfont zuobiao" style="font-size: 20px; margin-left: 10px; cursor: pointer"
                  @click="openMap"></i>
              </div>
            </el-form-item> -->

        <!-- <el-form-item size="small" label="描述" prop="description">
          <el-input type="textarea" :rows="2" placeholder="请输入" v-model="editForm.description"
            oninput="value=value.replace(/\s*/g,'')" @blur="editForm.description = $event.target.value" maxlength="30"
            resize="none" :autosize="{ minRows: 2, maxRows: 5 }">
          </el-input>
        </el-form-item> -->

        <!-- <el-form-item size="small" label="社区" >
              <el-select v-model="editForm.communityCode" clearable @change="changecommunity" style="width: 100%"
                placeholder="请选择社区">
                <el-option v-for="(item, i) in communityList" :key="i" :label="item.regionName"
                  :value="item.regionCode">
                </el-option>
              </el-select>
            </el-form-item> -->

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
        <el-button size="small" @click="submit" class="confirm-button">确 定</el-button>
      </span>

      <el-dialog width="50%" title="选择地区" :visible.sync="innerVisible" append-to-body :close-on-click-modal="false">
        <div class="mapLoc" v-if="isShowMap">
          <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless scrolling="no"></iframe>
        </div>
      </el-dialog>
    </el-dialog>

  </div>
</template>
<script>
import { reqOrgEdit, reqRegion, reqRegionLevel } from "@api/api.js";
import mixinRules from "./mixins/rules.js";
import { mapState } from "vuex";
import $ from "jquery";
import TreeSelSearch from "@components/TreeSelSearch.vue";

export default {
  props: ["editOrgInfo", "getLocationInfo", "getAddressflag", "flag"],
  mixins: [mixinRules],
  components: {
    TreeSelSearch,
  },
  data() {
    return {
      provinceList: [],
      cityList: [],
      areaList: [],
      streetList: [],
      communityList: [], //社区
      dialogVisible: false,
      innerVisible: false,
      editForm: {
        id: "",
        tenantId: "",
        type: "",
        orgName: "",
      },
      reqUrl:
        "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
      isShowMap: false,
      LocationInfo: true, //判断是否从地图选的经纬度
      activeNames: ['1', '2'],
      agencyTypeList: [
        {
          id: 2,
          name: "基础组织",
        },
        {
          id: 3,
          name: "行政区划",
        },
      ],
    };
  },
  computed: {
    ...mapState(["user", 'spacesManage']),
  },
  watch: {
    editOrgInfo: {
      handler(val) {
        this.editForm.id = val.id;
        this.editForm.orgName = val.orgName;
        this.editForm.type = val.type;
        this.editForm.parentName = val.parentName;
        this.editForm.parentId = val.parentId;
        this.$nextTick(() => {
          if(this.$refs.refTreeSelSearch){
            this.$refs.refTreeSelSearch.getDataList();
          }
        });
      },
      deep: true,
    },
    // getLocationInfo: {
    //   handler(val) {
    //     this.editForm.lat = val.getLat;
    //     this.editForm.lng = val.getLng;
    //     this.editForm.province = val.province;
    //     this.editForm.city = val.city;
    //     this.editForm.area = val.area;
    //     this.editForm.street = val.street;
    //     this.editForm.address = val.address == "我的位置" ? "" : val.address;
    //     // this.isShowMap = false;
    //     this.innerVisible = false;
    //     this.getRegion();
    //   },
    //   deep: true,
    // },
  },
  methods: {
    handleChange(val) {
      // console.log(val);
    },
    changeOrgId(id) {
      // console.log(id);
      this.editForm.parentId = id
    },
    // 根据省查询市
    async changprovince(val) {
      this.LocationInfo = false;
      this.editForm.address = "";
      this.cityList = [];
      this.editForm.city = "";
      this.editForm.cityCode = "";
      this.areaList = [];
      this.editForm.area = "";
      this.editForm.areaCode = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = [];
      this.editForm.community = "";
      this.editForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.cityList = res.data.rows;
      this.provinceList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.province = item.regionName;
          return;
        }
      });
    },
    // 根据市查询区
    async changcity(val) {
      this.LocationInfo = false;
      this.editForm.address = "";
      this.areaList = [];
      this.editForm.area = "";
      this.editForm.areaCode = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = [];
      this.editForm.community = "";
      this.editForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.areaList = res.data.rows;
      this.cityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.city = item.regionName;
          return;
        }
      });
    },
    // 根据区查询街道
    async changarea(val) {
      this.LocationInfo = false;
      this.editForm.address = "";
      this.streetList = [];
      this.editForm.street = "";
      this.editForm.streetCode = "";
      this.communityList = [];
      this.editForm.community = "";
      this.editForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.streetList = res.data.rows;
      this.areaList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.area = item.regionName;
          return;
        }
      });
    },
    // 街道名字赋值
    async changestreet(val) {
      this.communityList = [];
      this.editForm.community = "";
      this.editForm.communityCode = "";
      const res = await reqRegionLevel(val);
      this.communityList = res.data.rows;
      this.streetList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.street = item.regionName;
          return;
        }
      });
    },
    // 社区名称赋值
    changecommunity(val) {
      this.communityList.forEach((item) => {
        if (item.regionCode == val) {
          this.editForm.community = item.regionName;
          return;
        }
      });
    },
    // 省市区获取
    openMap() {
      this.isShowMap = true;
      if (this.editForm.lng == '') {
        this.reqUrl = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1`;
      } else {
        this.reqUrl = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${this.editForm.lng},${this.editForm.lat}`;
      }
      this.innerVisible = true;
    },
    // 查询省级行政组织
    async getRegion() {
      const res = await reqRegion();
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.province) {
          this.editForm.provinceCode = item.regionCode; //省行政码
          return;
        }
      });
      this.getRegionLevel();
    },
    // 查询省级下行政组织
    async getRegionLevel() {
      const res = await reqRegionLevel(this.editForm.provinceCode);
      this.cityList = res.data.rows;
      res.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.city) {
          this.editForm.cityCode = item.regionCode; //市行政码
          return;
        }
      });
      // 特殊市辖区查不到  默认选择第一个
      if (this.editForm.cityCode == "") {
        this.editForm.city = res.data.rows[0].regionName;
        this.editForm.cityCode = res.data.rows[0].regionCode;
      }

      const res2 = await reqRegionLevel(this.editForm.cityCode);
      this.areaList = res2.data.rows;
      if (this.editForm.area == "") return; //地图中没获取到区级不走下面
      res2.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.area) {
          this.editForm.areaCode = item.regionCode; //区行政码
          return;
        }
      });

      //   if (this.editForm.areaCode == "" || this.editForm.areaCode == null)
      //     return this.$modal.notifyWarning("数据异常，请联系管理员");
      const res3 = await reqRegionLevel(this.editForm.areaCode);
      this.streetList = res3.data.rows;
      if (this.editForm.street == "") return; //地图中没获取到街道不走下面
      res3.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.street) {
          this.editForm.streetCode = item.regionCode; //街道行政码
          return;
        }
      });

      const res4 = await reqRegionLevel(this.editForm.streetCode);
      this.communityList = res4.data.rows;
      if (this.editForm.community == "") return;
      res4.data.rows.forEach((item) => {
        if (item.regionName == this.editForm.community) {
          this.editForm.communityCode = item.regionCode;
          return;
        }
      });
    },

    // 查询省级行政组织
    async RegionList() {
      const res = await reqRegion();
      this.provinceList = res.data.rows;
    },
    // 市
    cityArr() {
      this.$nextTick(async () => {
        if (
          this.editForm.provinceCode == null ||
          this.editForm.provinceCode == ""
        )
          return;
        const res = await reqRegionLevel(this.editForm.provinceCode);
        this.cityList = res.data.rows;
      });
    },

    // 区
    areaArr() {
      this.$nextTick(async () => {
        if (this.editForm.cityCode == null || this.editForm.cityCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.cityCode);
        this.areaList = res.data.rows;
      });
    },

    // 街道
    RegionLevelList() {
      this.$nextTick(async () => {
        if (this.editForm.areaCode == null || this.editForm.areaCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.areaCode);
        this.streetList = res.data.rows;
      });
    },

    // 社区
    communitylList() {
      this.$nextTick(async () => {
        if (this.editForm.streetCode == null || this.editForm.streetCode == "")
          return;
        const res = await reqRegionLevel(this.editForm.streetCode);
        this.communityList = res.data.rows;
      });
    },

    // 点击编辑
    submit() {
      this.$refs.refForm.validate(async (valid) => {
        if (!valid) return;
        let {
          id,
          orgName,
          parentId,
        } = this.editForm;
        let params = {
          tenantId: this.user.tenantId,
          id,
          orgName,
          parentId
        };
        const res = await reqOrgEdit(params);
        if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        this.$modal.notifySuccess("编辑成功");
        this.$parent.Region();
        // this.$parent.loadChildren2(parentId);
        this.closeDialog();
      });
    },
    //地址转经纬度
    addrHand() {
      let that = this;
      // console.log(that.editForm.province + that.editForm.city + that.editForm.area + that.editForm.address);
      $.ajax({
        type: "get",
        dataType: "jsonp",
        data: {
          key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
          address:
            that.editForm.province +
            that.editForm.city +
            that.editForm.area +
            that.editForm.street +
            that.editForm.address, //具体的地址
          output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
        },
        jsonp: "callback",
        jsonpCallback: "QQmap",
        url: "https://apis.map.qq.com/ws/geocoder/v1/?",
        success: function (json) {
          // console.log(json)
          if (json.status == 0) {
            that.editForm.lng = json.result.location.lng;
            that.editForm.lat = json.result.location.lat;
            // console.log(that.editForm.lat);
            // console.log(that.editForm.lng);
            // that.$message({
            //   message: '成功获取位置的经纬度',
            //   type: 'success'
            // })
          } else {
            // that.$message.error('获取该位置经纬度失败')
          }
        },
        error: function (err) {
          // that.$message.error('异常错误，请刷新浏览器后重试')
        },
      });
    },
    // 点击关闭弹框
    closeDialog() {
      this.$refs.refForm.resetFields();
      this.dialogVisible = false;
      this.areaList = [];
      this.streetList = [];
      this.cityList = [];
      this.communityList = [];
      this.editForm = {
        parentId: "",
        tenantId: "",
        type: "",
        orgName: "",
      };
    },
  },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.mapLoc {
  height: 60vh;
  width: 100%;
  overflow-y: hidden;

  .iframe {
    width: 100%;
    height: 100%;
  }
}

.zuobiao {
  color: @primaryTxtcolor;
}

// 省市区/
::v-deep .el-input.is-disabled .el-input__inner {
  border-color: @primaryBorderColor !important;
}

// 折叠样式
.el_collapse {
  color: @primaryThemeTxtColor2;
}

::v-deep .el-collapse-item__header {
  // color: @primaryThemeTxtColor2;
  color: #7367F0 !important;
  width: 100px;
  height: 45px;
  line-height: 45px;
  font-size: 14px;
}

.el-collapse {
  border: none;
}

::v-deep .el-collapse-item__arrow {
  margin: 0;
}

::v-deep .el-collapse-item__content {
  padding-bottom: 0;
}

::v-deep .el-collapse-item__wrap {
  background: transparent;
}

// 折叠样式结束</style>
